package cn.tedu.zx.ams.adapter.serviceimpl;


import cn.tedu.zx.ams.adapter.mapper.AdminMapper;
import cn.tedu.zx.ams.adapter.mapper.AdminRoleMapper;

import cn.tedu.zx.ams.service.AdminService;
import cn.tedu.zx.common.exception.ServiceException;
import cn.tedu.zx.common.restful.JsonPage;
import cn.tedu.zx.pojo.admin.entity.Admin;
import cn.tedu.zx.pojo.admin.entity.AdminRole;
import cn.tedu.zx.pojo.admin.parm.AdminAccountUpdateParam;
import cn.tedu.zx.pojo.admin.parm.AdminAddNewParam;
import cn.tedu.zx.pojo.admin.parm.AdminDataUpdateParam;
import cn.tedu.zx.pojo.admin.parm.AdminLoginInfoParam;
import cn.tedu.zx.pojo.admin.vo.AdminDataVO;
import cn.tedu.zx.pojo.admin.vo.AdminDetailVO;
import cn.tedu.zx.pojo.admin.vo.AdminListItemVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
/*import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.crypto.password.PasswordEncoder;*/
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.io.File;
import java.time.LocalDateTime;
import java.util.*;

import static cn.tedu.zx.common.restful.ResponseCode.*;


@Service
@Slf4j
public class AdminServiceImpl implements AdminService {
//    @Value("${zx.jwt.secret-key}")
//    private String secretKey;//jwt密钥
//    @Value("${zx.jwt.duration-in-minute}")
//    private Long durationInMinute; // 密钥有效时间

    @Value("${zx.upload.base-dir}")
    private String imgUrl;

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private AdminRoleMapper adminRoleMapper;

    @Autowired
    PasswordEncoder passwordEncoder;

    //@Autowired
    // private AuthenticationManager authenticationManager;//（认证管理器）对象的

    @Override
    //添加管理员
    public void addNew(AdminAddNewParam adminAddNewParam) {
        log.debug("开始执行【添加管理员数据】的业务");
        checkAdminName(0L, adminAddNewParam.getUsername());
        checkPhone(0L, adminAddNewParam.getPhone());
        checkEmail(0L, adminAddNewParam.getEmail());


        {
            Admin admin = new Admin();
            BeanUtils.copyProperties(adminAddNewParam, admin);
            admin.setCreated(LocalDateTime.now());
            admin.setUpdated(LocalDateTime.now());
            admin.setPassword(passwordEncoder.encode(admin.getPassword()));

            int rows = adminMapper.insert(admin);

            if (rows != 1) {
                String message = "添加管理员失败，服务器忙，请稍后再试！";
                log.warn(message);
                throw new ServiceException(ERR_INSERT, message);
            }
            addNewAdminRole(admin.getId(), adminAddNewParam.getRoleIds());
        }//把添加的管理员数据写入数据库中
        log.debug("已完成【添加管理员数据】的业务");
    }


    @Override
    //根据管理员删除ID
    public void delete(Long id) {
        log.debug("开始执行【删除管理员数据】的业务");
        checkId(id);

        deleteImg(id);//调用删除图片方法

        //判断是否为超级管理员，是则无法删除
        String[] superAdmin = adminMapper.isSuperAdmin(id);
        for (String s : superAdmin) {
            boolean SA = s.equals("超级管理员");
            if (SA == true) {
                String message = "无法删除超级管理员，";
                log.warn(message);
                throw new ServiceException(ERR_DELETE, message);
            }
        }

        deleteAdminRoleById(id);


        {
            log.debug("即将从admin表删除管理员数据，id：{}", id);
            int delete = adminMapper.deleteById(id);// 删除管理员
            if (delete != 1) {
                String message = "删除管理员失败，服务器忙，请稍后再尝试！";
                log.warn(message);
                throw new ServiceException(ERR_DELETE, message);
            }


        }//删除管理员与角色的关联数据
        log.debug("已完成【删除管理员数据】的业务");
    }

    @Override
    //修改数据
    public void updateDataById(AdminDataUpdateParam adminDataUpdateParam) {
        log.debug("开始执行【修改管理员数据】的业务");
        checkId(adminDataUpdateParam.getId());
        checkPhone(adminDataUpdateParam.getId(), adminDataUpdateParam.getPhone());
        checkEmail(adminDataUpdateParam.getId(), adminDataUpdateParam.getEmail());

        {
            Admin admin = new Admin();
            BeanUtils.copyProperties(adminDataUpdateParam, admin);
            admin.setUpdated(LocalDateTime.now());


/*// 删除本地图片
            AdminDetailVO adminDetailVO = adminMapper.selectDetailById(adminDataUpdateParam.getId());
            String icon = adminDetailVO.getIcon();
            String url="D:/cream/Desktop/zx-upload/"+icon;

            File file = new File(url);
            if (file.exists()){
                System.out.println("查询到头像是存在");
                file.delete();
                System.out.println("删除成功");
            }*/

            deleteImg(adminDataUpdateParam.getId());//调用删除图片方法
            int updateRows = adminMapper.updateById(admin);
            if (updateRows != 1) {
                String message = "服务器忙,请稍后再试";
                log.warn(message);
                throw new ServiceException(ERR_UNKNOWN, message);
            }
            deleteAdminRoleById(adminDataUpdateParam.getId());
            addNewAdminRole(admin.getId(), adminDataUpdateParam.getRoleIds());
        }//尝试修改用户
        log.debug("已完成【修改管理员数据】的业务");
    }

    private void deleteImg(Long id) {
        AdminDetailVO adminDetailVO = adminMapper.selectDetailById(id);
        String icon = adminDetailVO.getIcon();
        String newUrl = imgUrl + icon;

        File file = new File(newUrl);
        if (file.exists()) {
            System.out.println("查询到头像是存在");
            file.delete();
            System.out.println("删除成功");
        }
    }//检查删除原有图片占用情况


    @Override
    //修改账户禁用情况
    public void updateIsEnableById(Long id, Integer isEnable) {
        log.debug("开始执行【修改管理员启用值】的业务");
        checkId(id);
        {
            if (isEnable != 1 && isEnable != 0) {
                String message = "修改账户状态失败，状态码出现异常！";
                log.warn(message);
                throw new ServiceException(NOT_FOUND, message);
            }
        }//检查状态码是否为0或1

        //判断是否为超级管理员，是则无法删除
        String[] superAdmin = adminMapper.isSuperAdmin(id);
        for (String s : superAdmin) {
            boolean SA = s.equals("超级管理员");
            if (SA == true) {
                String message = "无法修改超级管理员的启用状态，";
                log.warn(message);
                throw new ServiceException(ERR_UPDATE, message);
            }
        }

        {
            Admin admin = new Admin();
            admin.setId(id);
            admin.setIsEnable(isEnable);
            int row = adminMapper.updateById(admin);
            if (row != 1) {
                String message = "修改账户状态失败，服务器忙，请稍后再试！";
                log.warn(message);
                throw new ServiceException(ERR_INSERT, message);
            }
        }//尝试更改账户状态
        log.debug("已完成【修改管理员启用值】的业务");
    }

    @Override
    //修改账户隐私数据
    public void updateAccount(AdminAccountUpdateParam adminAccountUpdateParam) {
        log.debug("开始执行【修改管理员隐私数据】的业务");
        checkId(adminAccountUpdateParam.getId());
        checkAdminName(adminAccountUpdateParam.getId(), adminAccountUpdateParam.getAdminName());
        {
            Admin admin = new Admin();
            String encode = passwordEncoder.encode(adminAccountUpdateParam.getPassword());
            BeanUtils.copyProperties(adminAccountUpdateParam, admin);
            admin.setPassword(encode);
            int rows = adminMapper.updateById(admin);
            if (rows != 1) {
                String message = "修改账户信息失败，服务器忙，请稍后再试！";
                log.warn(message);
                throw new ServiceException(ERR_INSERT, message);
            }
        }//尝试修改账户隐私数据
        log.debug("已完成【修改管理员隐私数据】的业务");
    }

    @Override
    public AdminDetailVO detail(Long id) {
        checkId(id);
        return adminMapper.selectDetailById(id);
    }

    private void checkAdminName(Long id, String adminName) {
        QueryWrapper<Admin> queryAdminName = new QueryWrapper<>();
        queryAdminName.eq("username", adminName).ne("id", id);
        int countByName = adminMapper.selectCount(queryAdminName);
        if (countByName > 0) {
            String message = "管理员名称被占用";
            log.warn(message);
            throw new ServiceException(CONFLICT, message);
        }
    }//检查admin_name占用情况

    private void checkPhone(Long id, String phone) {
        QueryWrapper<Admin> queryAdminName = new QueryWrapper<>();
        queryAdminName.eq("phone", phone).ne("id", id);
        int countByName = adminMapper.selectCount(queryAdminName);
        if (countByName > 0) {
            String message = "管理员电话号码被占用";
            log.warn(message);
            throw new ServiceException(CONFLICT, message);
        }
    }//检查phone占用情况

    private void checkEmail(Long id, String email) {
        QueryWrapper<Admin> queryAdminName = new QueryWrapper<>();
        queryAdminName.eq("email", email).ne("id", id);
        int countByName = adminMapper.selectCount(queryAdminName);
        if (countByName > 0) {
            String message = "管理员邮箱被占用";
            log.warn(message);
            throw new ServiceException(CONFLICT, message);
        }
    }//检查email占用情况

    private void checkId(Long id) {
        QueryWrapper<Admin> queryAdminName = new QueryWrapper<>();
        queryAdminName.eq("id", id);
        int countByName = adminMapper.selectCount(queryAdminName);
        if (countByName == 0) {
            String message = "管理员id不存在";
            log.warn(message);
            throw new ServiceException(NOT_FOUND, message);
        }
    }//检查id是否存在

    private void deleteAdminRoleById(Long id) {
        int deleteCount = adminRoleMapper.deleteByAdminId(id);
        if (deleteCount < 1) {
            String message = "未能成功删除管理员角色";
            log.warn(message);
            throw new ServiceException(ERR_DELETE, message);
        }
    }//删除用户id对应的用户角色关联表

    private void addNewAdminRole(Long id, Long[] roleIds) {
        for (Long roleId : roleIds) {
            AdminRole adminRole = new AdminRole();
            adminRole.setAdminId(id);
            adminRole.setRoleId(roleId);
            adminRole.setCreated(LocalDateTime.now());
            adminRole.setUpdated(LocalDateTime.now());
            int insertCount = adminRoleMapper.insert(adminRole);
            if (insertCount != 1) {
                String message = "添加管理员角色失败";
                log.warn(message);
                throw new ServiceException(ERR_INSERT, message);
            }
        }
    }//新增用户id对应的用户角色关联表


    @Override
    public JsonPage<AdminListItemVO> list(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<AdminListItemVO> list = adminMapper.List();
        PageInfo<AdminListItemVO> pageInfo = new PageInfo(list);
        log.info(pageInfo + "");
        return JsonPage.restPage(pageInfo);
    }

    @Override
    public AdminDataVO adminData(String username) {
        return adminMapper.adminData(username);
    }
}
